package com.ssh.test;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class BlockingQ extends Thread {
	public static void main(String[] args) {
		new BlockingQ("A").start();
		new BlockingQ("B").start();
		new BlockingQ("C").start();
	}

	// 需要注意blockingqueue设计为static 而count不能设计为static 两点乃是关键
	private static String currentThread = "A";
	private static BlockingQueue<String> blockingQ = new ArrayBlockingQueue<String>(1);
	private String name = "";
	private int count = 10;

	public BlockingQ(String name) {
		this.name = name;
	}

	@Override
	public void run() {
		while (count > 0) {
			try {
				blockingQ.put(name);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			if (currentThread.equals(this.name)) {
				try {
					System.out.print(blockingQ.take());
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				count--;
				System.out.println("currThread:" + name + "---执行-1操作" + count);
				if (currentThread.equals("A")) {
					currentThread = "B";
				} else if (currentThread.equals("B")) {
					currentThread = "C";
				} else if (currentThread.equals("C")) {
					currentThread = "A";
					System.out.println();
				}
			} else {
				try {
					blockingQ.take();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
}